import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { useSearchParams } from "react-router-dom";
import { information_getchatHistory } from '../request/api';
import { NavBar, Space, Toast } from 'antd-mobile'
import { CloseOutline, MoreOutline, SearchOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom';
const ChatContainer = styled.div`
  width: 100%;
  height: 90vh;
  background-color: white;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
`;

const MessageList = styled.div`
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  overflow: auto;
`;

const Message = styled.div`
  padding: 8px 12px;
  margin: 0.2083rem;
  border-radius: 8px;
  max-width: 60%;
  word-wrap: break-word;
  ${({ isme }) =>
        isme
            ? `
      align-self: flex-end;
      margin-left: 8.3333rem;
      background-color: #DCF8C6;
    `
            : `
      align-self: flex-start;
      background-color: #E5E5EA;
    `}
`;
const InputContainer = styled.div`
  display: flex;
  padding: 10px;
  border-top: 1px solid #ccc;
`;
const InputField = styled.input`
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
`;
const SendButton = styled.button`
  padding: 8px 15px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;

  &:hover {
    background-color: #0056b3;
  }
`;
const ZinLT = () => {
    const nav= useNavigate()
    const myID = JSON.parse(localStorage.getItem('userInformation')).arr._id

    const [params, setParams] = useSearchParams()
    let yourId = params.get('yourId');

    const [messages, setMessages] = useState([]);
    const [inputValue, setInputValue] = useState('');
    const [socket, setSocket] = useState(null);
    const right = (
        <div style={{ fontSize: 24 }}>
            <Space style={{ '--gap': '16px' }}>
                <MoreOutline />
            </Space>
        </div>
    )
    const back = () =>{
        nav(-1)
        
    }
    useEffect(()=>{
        var div = document.querySelector('.sc-gnOvAp');
        div.scrollTop = div.scrollHeight; // 滚动到最底部
    },[messages])
    useEffect(() => {

        console.log("接收人的信息", yourId);
        information_getchatHistory({ myId: myID, yourId: yourId }).then(res => {
            console.log("获取到的聊天记录", res.data.ChatList);
            setMessages(res.data.ChatList)
        })
    }, [])
    useEffect(() => {
        const newSocket = new WebSocket(`ws://localhost:3000?userId=${myID}`);
        setSocket(newSocket);

        newSocket.onopen = () => {
            console.log('WebSocket 连接已建立');
        };

        newSocket.onmessage = (event) => {
            const newMessage = JSON.parse(event.data);
            setMessages((prevMessages) => [...prevMessages, newMessage]);
        };

        newSocket.onclose = () => {
            console.log('WebSocket 连接已关闭');
        };

        return () => {
            newSocket.close();
        };
    }, []);

    // 发送信息
    const handleSendMessage = () => {
        if (inputValue.trim() === '') return;
        const newMessage = {
            senderId: myID,
            recipientId: yourId,
            content: inputValue,
            dateTime: Date.now()
        };
        if (socket) {
            socket.send(JSON.stringify(newMessage));
            setMessages((prevMessages) => [...prevMessages, newMessage]);
            setInputValue('');
        }
    };

    return (
        <>
            <NavBar right={right} onBack={back}>
                标题
            </NavBar>
            <ChatContainer>
                <MessageList>
                    {messages.map((message, index) => (
                        <Message key={index} isme={message.senderId._id === myID || message.senderId === myID}>
                            {message.content}
                        </Message>
                    ))}
                </MessageList>
                <InputContainer>
                    <InputField
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        placeholder="输入消息"
                    />
                    <SendButton onClick={handleSendMessage}>发送</SendButton>
                </InputContainer>
            </ChatContainer>
        </>
    );
};

export default ZinLT;